package fun.carliels.doraemon.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

/**
 * 字符串工具
 */
public class StringKit {

    private static final Logger logger = LoggerFactory.getLogger(StringKit.class);

    private static final String EMPTY = "";

    /**
     * 安全取值
     * <p>如果str为空或者null, 则返回safeStr</p>
     * @param str
     * @param safeStr
     * @return
     */
    public static final String getSafety(String str, String safeStr) {
        return StringUtils.isBlank(str) ? safeStr : str;
    }

    /**
     * 压缩字符串
     * @param text
     * @return
     */
    public static String compress(String text)  {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(out)) {
                deflaterOutputStream.write(text.getBytes(StandardCharsets.UTF_8));
            }
            return new String(Base64.getEncoder().encode(out.toByteArray()));
        } catch (IOException e) {
            logger.error("压缩文本失败:{}", text, e);
        }
        return EMPTY;
    }

    /**
     * 解压缩
     * @param text
     * @return
     * @throws IOException
     */
    public static String uncompress(String text) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            try (OutputStream outputStream = new InflaterOutputStream(os)) {
                outputStream.write(Base64.getDecoder().decode(text));
            }
            return new String(os.toByteArray(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            logger.error("解压文本失败:{}", text, e);
        }
        return EMPTY;
    }

    public static void main(String[] args) {
        String source = "100243123456002351012398100034000000";
        System.out.println("source:"+source+"["+source.length()+"]");
        String compress = StringKit.compress(source);
        System.out.println("compress:"+compress+"["+compress.length()+"]");
        String uncompress = StringKit.uncompress(compress);
        System.out.println("uncompress:"+uncompress+"["+uncompress.length()+"]");
    }
}
